package zy.blue7.im;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import zy.blue7.im.common.message.Message;
import zy.blue7.im.core.codec.MessageCodec;
import zy.blue7.im.core.codec.MessageInfoCodec;
import zy.blue7.im.gui.ChatIndexFrame;
import zy.blue7.im.handler.ClientMessageHandler;

import java.net.InetSocketAddress;

/**
 * @author blue7
 * @version 1.0
 * @date 2022/3/1 16:24
 */
public class Client {

    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Client().startClient();
    }

    public static Channel startClient() throws InterruptedException {
        return new Bootstrap()
                // 2.添加 EventLoop
                .group(new NioEventLoopGroup())
                //3. 选择客户端 channel实现
                .channel(NioSocketChannel.class)
                //4.添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override // todo 在建立链接的时候调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MessageInfoCodec());
                        ch.pipeline().addLast(new MessageCodec());
//                        ch.pipeline().addLast(new MessageInfoDecoder());
//                        ch.pipeline().addLast(new MessageInfoEncoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<Message>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
                                System.out.println("客户端收到消息：" + message);

                                ClientMessageHandler messageHandler = ClientContainer.handlerMap.get(message.getClass());

                                messageHandler.handle(ctx.channel(), message, ChatIndexFrame.textArea);
                            }

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                ctx.channel().close();
                            }
                        });
                    }
                })
                //5.连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                .sync() //todo 阻塞方法，知道链接建立
                .channel();
    }
}
